package com.justyh.ssm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justyh.ssm.service.TranslateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/trans")
public class TranslateController {

    @Autowired
    private TranslateService translateService;
    @RequestMapping(path={"/",""},method = {RequestMethod.GET})
    public Object index(){
        return new ModelAndView("translate");
    }

    @RequestMapping(path="/translate",method = {RequestMethod.GET},produces = "application/html;charset=UTF-8")
    public Object translate(@RequestParam String query,
                            @RequestParam String from,
                            @RequestParam String to){
        if(query==null||"".equals(query)){
            return "";
        }
        String result=translateService.getTransResult(query,from,to);
        JSONObject jsonObject= JSON.parseObject(result);
        JSONArray transResult=jsonObject.getJSONArray("trans_result");
        if(transResult==null){
            return "";
        }
        JSONObject itemObject=transResult.getJSONObject(0);
        return itemObject.get("dst").toString();
    }

    @RequestMapping(path="/languages")
    public Object getLanguageList(){
       return translateService.getAllLanguages();
    }

}
